package io.kimmking.rpcfx.client;

import io.kimmking.rpcfx.api.RpcfxResponse;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;

import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author lv
 * @date 2021/5/30 17:11
 */
public class HttpClient {
    //线程组
    //private static final EventLoopGroup group = new NioEventLoopGroup();
    //启动类
    ///private static final Bootstrap bootstrap = new Bootstrap();
    private  RpcfxResponse rpcfxResponse = new RpcfxResponse();
    public RpcfxResponse start(String url,String body) throws InterruptedException, MalformedURLException {
        //线程组
        final EventLoopGroup group = new NioEventLoopGroup();
        //启动类
        final Bootstrap bootstrap = new Bootstrap();
        URL uri = new URL(url);
        int port = uri.getPort() == -1 ? 80 : uri.getPort();

        try {
            bootstrap.group(group)
                .remoteAddress(new InetSocketAddress(uri.getHost(), port))
                //长连接
                .option(ChannelOption.SO_KEEPALIVE, true)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    protected void initChannel(Channel channel) throws Exception {

                        //包含编码器和解码器
                        channel.pipeline().addLast(new HttpClientCodec());

                        //聚合
                        channel.pipeline().addLast(new HttpObjectAggregator(1024 * 10 * 1024));

                        //解压
                        channel.pipeline().addLast(new HttpContentDecompressor());

                        channel.pipeline().addLast(new ClientHandler(url,body,rpcfxResponse));
                    }
                });

            ChannelFuture channelFuture = bootstrap.connect().sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
        System.out.println(rpcfxResponse.getResult());
        return rpcfxResponse;
    }

    public static void main(String[] args) throws InterruptedException, MalformedURLException {
        System.out.println("1");
        new HttpClient().start("http://127.0.0.1:8080","{\"method\":\"findById\",\"params\":[1],\"serviceClass\":\"io.kimmking.rpcfx.demo.api.UserService\"}");

    }
}
